/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.formmetadata.i18n.component.strategy.idstrategy;

import com.inspur.edp.web.common.utility.StringUtility;

import java.util.HashMap;

/**
 * 组件id生成factory
 * @author  noah
 */
public class ComponentIdFactory {
    private ComponentIdFactory() {
    }

    /**
     * 静态单例属性
     */
    private static final ComponentIdFactory Instance = new ComponentIdFactory();

    public static ComponentIdFactory getInstance() {
        return Instance;
    }

    /**
     * 缓存字典 避免重复创建
     */
    private final HashMap<String, IComponentIdStrategy> componentIdStrategyDictionary = new HashMap<>();

    /**
     * 根据组件Id类型创建组件Id策略
     *
     * @return
     */
    public final IComponentIdStrategy creatComponentIdStrategy(String componentIdType) {
        if (StringUtility.isNullOrEmpty(componentIdType)) {
            return null;
        }


        // 如果缓存字典中已包含 那么从缓存中读取该实例
        if (componentIdStrategyDictionary.containsKey(componentIdType)) {
            return componentIdStrategyDictionary.get(componentIdType);
        }

        IComponentIdStrategy componentIdStrategy;
        if (ComponentIdType.HTML_TEMPLATE.equals(componentIdType)) {
            componentIdStrategy = new HtmlTemplateIdStrategy();
        } else {
            componentIdStrategy = new DefaultIdStrategy();
        }

        // 默认的策略不缓存
        if (componentIdStrategy != null) {
            componentIdStrategyDictionary.put(componentIdType, componentIdStrategy);
        }

        return componentIdStrategy;
    }
}
